/*
 * Copyright 2019-2021 the original author or authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cool.houge.ws.main;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import cool.houge.lang.NanoIdUtils;
import cool.houge.ws.ConfigKeys;
import io.avaje.inject.BeanScope;
import io.avaje.inject.InjectModule;
import java.time.Duration;
import java.time.Instant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 程序入口.
 *
 * @author KK (kzou227@qq.com)
 */
@InjectModule(
        name = "Houge",
        requires = {Config.class})
public class Application {

    private static final Logger log = LogManager.getLogger();
    private static final String CONFIG_FILE = "houge.conf";
    private final Config config;

    {
        this.config = ConfigFactory.load(CONFIG_FILE);
        log.info("应用配置加载成功 {}", CONFIG_FILE);
    }
    // ========================================================================== //
    {
        // 初始化 IoC 容器
        var beanScope = BeanScope.builder()
                .bean(Config.class, config)
                .shutdownHook(true)
                .build();
        log.info("IoC 容器初始化完成 @{}", beanScope.hashCode());
        log.info("==================== {}", config.getString(ConfigKeys.APP_NAME));
    }

    public static void main(String[] args) {
        System.setProperty(ConfigKeys.APP_NAME, NanoIdUtils.randomNanoId());

        var s1 = Instant.now();
        new Application();
        var s2 = Instant.now();
        log.info("应用启动成功（耗时 {}ms）", Duration.between(s1, s2).toMillis());
    }
}
